<?php

namespace backend\models\system\search;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\system\Admin;

/**
 * AdminSearch represents the model behind the search form of `common\models\system\Admin`.
 */
class AdminSearch extends Admin
{
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['uid', 'reg_time', 'reg_ip', 'last_login_time', 'last_login_ip', 'updated_at', 'status'], 'integer'],
            [['username', 'password', 'salt', 'email', 'mobile', 'nickname','role'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Admin::find()
            ->alias('a')
            ->joinWith(['authAssignment aa']);

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!empty($params['role'])) {
            $this->role = $params['role'];
        }

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'a.uid' => $this->uid,
            'a.reg_time' => $this->reg_time,
            'a.reg_ip' => $this->reg_ip,
            'a.last_login_time' => $this->last_login_time,
            'a.last_login_ip' => $this->last_login_ip,
            'a.updated_at' => $this->updated_at,
            'a.status' => $this->status,
            'aa.item_name' => $this->role,
        ]);

        $query->andFilterWhere(['like', 'a.username', $this->username])
            ->andFilterWhere(['like', 'a.password', $this->password])
            ->andFilterWhere(['like', 'a.salt', $this->salt])
            ->andFilterWhere(['like', 'a.email', $this->email])
            ->andFilterWhere(['like', 'a.mobile', $this->mobile])
            ->andFilterWhere(['like', 'a.nickname', $this->nickname]);

        return $dataProvider;
    }
}
